package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.model.mongo.RecommendUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

//查询redis中的推荐数据
@DubboService
public class RecommendUserApiImpl implements  RecommendUserApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override  //今日佳人
    public RecommendUser todayBest(Long toUserId) {
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //从高到底排序，每次差1条，从0条开始查
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score"))).limit(1).skip(0);
        RecommendUser one = mongoTemplate.findOne(query, RecommendUser.class);
        //如果刚注册，没推荐，构造默认数据
        if (one==null){
           one = new RecommendUser();
           one.setToUserId(toUserId);
           one.setUserId(1l);
           one.setScore(95d);
        }
        return one;
    }

    //查询首页推荐朋友
    public List<RecommendUser> pageList(Long userId,Integer page,Integer pageSize) {
        Criteria criteria = Criteria.where("toUserId").is(userId);
        Query query = Query.query(criteria);
        long count = mongoTemplate.count(query, RecommendUser.class);
        System.out.println("总数"+count);
        query.with(Sort.by(Sort.Order.desc("score"))).limit(pageSize).skip(pageSize * (page - 1));
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);
        return recommendUsers;
    }

    //查询佳人详细信息
    public RecommendUser selectByUserId(Long id, Long userId) {
        Criteria criteria = Criteria.where("userId").is(id).and("toUserId").is(userId);
        Query query = Query.query(criteria);
        RecommendUser one = mongoTemplate.findOne(query, RecommendUser.class);
        //如果是新用户，可能没有推荐数据信息以及缘分值，则设置默认
        if (one==null){
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(id);
            recommendUser.setToUserId(userId);
            recommendUser.setScore(95d);
        }
        return one;
    }
}
